﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class ucSqlOperater : UserControl
    {
        string[] keystr = { "select ",
            "from ", "where ", " and ", " or ", " order ",
            " by ", " desc ", " when ", " case ",
            " then ", " end ", " on ", " in ", " is ",
            " else ", " left ", " join ", " not ", " null " };

        public ucSqlOperater()
        {
            InitializeComponent();
        }

        //组装请求参数
        private string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        public int getbunch(string p, string s)  //给关键字上色
        {
            int cnt = 0; int M = p.Length; int N = s.Length;
            char[] ss = s.ToCharArray(), pp = p.ToCharArray();
            if (M > N) return 0;
            for (int i = 0; i < N - M + 1; i++)
            {
                int j;
                for (j = 0; j < M; j++)
                {
                    if (ss[i + j] != pp[j]) break;
                }
                if (j == p.Length)
                {
                    this.rchTextSql.Select(i, p.Length);
                    this.rchTextSql.SelectionColor = Color.Blue;
                    cnt++;
                }
            }
            return cnt;

        }


        public List<JObject> GetDataSet(string sql)
        {
            string url = "http://localhost:3000/base/getdataset";
            string val = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.Accept = "text/html,application/xhtml+html,*/*";
            request.ContentType = "application/json;charset=utf-8";
            var type = request.GetType();
            var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);
            var methodType = currentMethod.GetType();
            methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);


            string data = "{\"sql\":\"" + sql + "\"}";
            var jObject = JObject.Parse(data);
            using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
            {
                requestStream.Write(data);
            }

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                val = reader.ReadToEnd();
            }
            List<JObject> staffs = JsonConvert.DeserializeObject<List<JObject>>(val);
            return staffs;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                List<JObject> dt = GetDataSet(this.rchTextSql.Text.Trim());
                dataGridView1.DataSource = dt; //dt.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请输入正确的SQL语句! 错误原因：" + ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error); ;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void rchTextSql_TextChanged(object sender, EventArgs e)
        {
            int index = this.rchTextSql.SelectionStart;    //记录修改的位置
            this.rchTextSql.SelectAll();
            this.rchTextSql.SelectionColor = Color.Black;

            for (int i = 0; i < keystr.Length; i++)
                this.getbunch(keystr[i], this.rchTextSql.Text);

            this.rchTextSql.Select(index, 0);     //返回修改的位置
            this.rchTextSql.SelectionColor = Color.Black;
        }
    }
}
